package jsr203.sun.nio.fs;

import java.lang.reflect.Field;
import java.nio.ByteBuffer;

import sun.misc.Unsafe;

final class CopyMemory {
  private static final Unsafe unsafe = initializeUnsafe();
  
  private static Unsafe initializeUnsafe() {
    try {
      Field field = Unsafe.class.getDeclaredField("theUnsafe");
      field.setAccessible(true);
      return (Unsafe) field.get(null);    
    } catch (SecurityException e) {
      throw new RuntimeException("Unable to initialize Unsafe", e);
    } catch (NoSuchFieldException e) {
      throw new RuntimeException("Unable to initialize Unsafe", e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException("Unable to initialize Unsafe", e);
    }
  }  
  
  public static Unsafe getUnsafe() {
    return unsafe;
  }

  public static void toByteArray(long src, byte[] dest, long len) {
    for (int i = 0; i < len; i++) {
      dest[i] = unsafe.getByte(src + i);      
    }
  }
  
  public static void fromByteArray(byte[] src, long dest, long len) {
    for (int i = 0; i < len; i++) {
      unsafe.putByte(dest + i, src[i]);
    }
  }
  
  public static void toByteBuffer(
      long src, ByteBuffer dest, int offset, int len) {
    for (int i = 0; i < len; i++) {
      dest.put(offset + i, unsafe.getByte(src + i));      
    }
  }
  
  public static void fromByteBuffer(
      ByteBuffer src, int offset, long dest, long len) {
    for (int i = 0; i < len; i++) {
      unsafe.putByte(dest + i, src.get(offset + 1));
    }
  }  
}
